import React from "react";
import { Link, useNavigate, useLocation } from "react-router-dom";
import withRouter from "../../utils/withRouter";
import Logo from "../../assets/images/logo192.png";
import "./index.less";
import {
  AppstoreOutlined,
  HomeOutlined,
  BarsOutlined,
  ToolOutlined,
  UserOutlined,
  SafetyOutlined,
  AreaChartOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
} from "@ant-design/icons";
import { Layout, Menu } from "antd";

const { Sider } = Layout;

function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type,
  };
}

const menuList = [
  getItem("首页", "home", <HomeOutlined />),
  getItem("商品", "products", <AppstoreOutlined />, [
    getItem("品类管理", "products/category", <BarsOutlined />),
    getItem("商品管理", "products/product", <ToolOutlined />),
  ]),
  getItem("用户管理", "user", <UserOutlined />),
  getItem("角色管理", "role", <SafetyOutlined />),
  getItem("图形图表", "charts", <AreaChartOutlined />, [
    getItem("柱形图", "charts/bar", <BarChartOutlined />),
    getItem("线形图", "charts/line", <LineChartOutlined />),
    getItem("饼图", "charts/pie", <PieChartOutlined />),
  ]),
];

// 根据角色权限过滤菜单项
const filterMenuItems = (menuItems, menus) => {
  // 去掉前导斜杠
  menus = menus.map((menu) => (menu.startsWith("/") ? menu.slice(1) : menu));

  // 创建一个集合以跟踪所有需要的菜单项
  const includedKeys = new Set();

  // 查找所有父节点并添加到集合中
  const findParents = (items) => {
    items.forEach((item) => {
      if (item.children) {
        findParents(item.children); // 递归查找子节点
        // 如果任何子节点被选中，则包括当前节点
        const hasCheckedChildren = item.children.some((child) =>
          includedKeys.has(child.key)
        );
        if (hasCheckedChildren || menus.includes(item.key)) {
          includedKeys.add(item.key);
        }
      }
      // 添加当前项
      if (menus.includes(item.key)) {
        includedKeys.add(item.key);
      }
    });
  };

  findParents(menuItems);

  // 过滤菜单项
  const filterItems = (items) => {
    return items.reduce((acc, item) => {
      if (item.children) {
        const children = filterItems(item.children);
        if (children.length > 0 || includedKeys.has(item.key)) {
          acc.push({ ...item, children });
        }
      } else if (includedKeys.has(item.key)) {
        acc.push(item);
      }
      return acc;
    }, []);
  };

  return filterItems(menuItems);
};

const LeftNav = ({ collapsed }) => {
  const navigate = useNavigate();
  const location = useLocation();

  // 获取当前用户信息
  const user = JSON.parse(localStorage.getItem("user_key"));
  const { role } = user;

  // 检查是否是 admin
  const isAdmin = user.username === "admin"; // 假设角色信息包含名称，实际使用中根据实际数据调整

  // 处理菜单项
  const menuItems = isAdmin ? menuList : filterMenuItems(menuList, role.menus);

  const items = menuItems;

  console.log("items", items);

  const handleMenuClick = (e) => {
    const { key } = e;
    navigate(`/${key}`);
  };

  // 根据当前路径设置 selectedKeys
  const selectedKeys = items.reduce((acc, item) => {
    if (item.children) {
      const childKey = item.children.find((child) =>
        location.pathname.startsWith(`/${child.key}`)
      );
      if (childKey) {
        acc.push(childKey.key);
      }
    } else if (location.pathname.startsWith(`/${item.key}`)) {
      acc.push(item.key);
    }
    return acc;
  }, []);

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className={`logo ${collapsed ? "collapsed" : ""}`}>
        <Link className="left-nav-link" to="/home">
          <img src={Logo} alt="logo" />
          <h1>奇宇轩昂后台</h1>
        </Link>
        <Menu
          onClick={handleMenuClick}
          defaultSelectedKeys={["home"]}
          selectedKeys={selectedKeys}
          defaultOpenKeys={["products"]}
          mode="inline"
          theme="dark"
          inlineCollapsed={collapsed}
          items={items}
        />
      </div>
    </Sider>
  );
};

export default withRouter(LeftNav);
